"""
后台管理服务 - PyQt5界面
"""
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
                             QHBoxLayout, QLabel, QLineEdit, QPushButton,
                             QTableWidget, QTableWidgetItem, QTabWidget,
                             QMessageBox, QHeaderView, QGroupBox, QComboBox)
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QIcon
from database import Database, AccountManager, ClientManager
from socket_server import SocketServer
import threading
import os


class AdminServerWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.db = Database()
        self.account_manager = AccountManager(self.db)
        self.client_manager = ClientManager(self.db)
        self.socket_server = SocketServer()
        self.server_thread = None
        self.init_ui()
        self.start_refresh_timer()

    def init_ui(self):
        """初始化界面"""
        self.setWindowTitle("VPN后台管理服务")
        self.setGeometry(100, 100, 1000, 700)
        
        # 设置窗口图标
        if os.path.exists('icon.png'):
            self.setWindowIcon(QIcon('icon.png'))
        
        # 主窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout()
        central_widget.setLayout(layout)
        
        # 标题和服务器控制
        header_layout = QHBoxLayout()
        title = QLabel("VPN后台管理服务")
        title.setStyleSheet("font-size: 18px; font-weight: bold;")
        header_layout.addWidget(title)
        
        header_layout.addStretch()
        
        self.server_status_label = QLabel("服务器状态: 未启动")
        self.server_status_label.setStyleSheet("color: red; font-weight: bold;")
        header_layout.addWidget(self.server_status_label)
        
        self.start_server_button = QPushButton("启动服务器")
        self.start_server_button.clicked.connect(self.toggle_server)
        header_layout.addWidget(self.start_server_button)
        
        layout.addLayout(header_layout)
        
        # 标签页
        tabs = QTabWidget()
        layout.addWidget(tabs)
        
        # 账号管理标签页
        account_tab = self.create_account_tab()
        tabs.addTab(account_tab, "账号管理")
        
        # 客户端管理标签页
        client_tab = self.create_client_tab()
        tabs.addTab(client_tab, "客户端管理")

    def create_account_tab(self):
        """创建账号管理标签页"""
        widget = QWidget()
        layout = QVBoxLayout()
        widget.setLayout(layout)
        
        # 添加账号组
        add_group = QGroupBox("添加账号")
        add_layout = QVBoxLayout()
        
        username_layout = QHBoxLayout()
        username_layout.addWidget(QLabel("用户名:"))
        self.new_username_input = QLineEdit()
        username_layout.addWidget(self.new_username_input)
        add_layout.addLayout(username_layout)
        
        password_layout = QHBoxLayout()
        password_layout.addWidget(QLabel("密码:"))
        self.new_password_input = QLineEdit()
        self.new_password_input.setEchoMode(QLineEdit.Password)
        password_layout.addWidget(self.new_password_input)
        add_layout.addLayout(password_layout)
        
        add_button = QPushButton("添加账号")
        add_button.clicked.connect(self.add_account)
        add_layout.addWidget(add_button)
        
        add_group.setLayout(add_layout)
        layout.addWidget(add_group)
        
        # 账号列表
        list_group = QGroupBox("账号列表")
        list_layout = QVBoxLayout()
        
        self.account_table = QTableWidget()
        self.account_table.setColumnCount(2)
        self.account_table.setHorizontalHeaderLabels(["用户名", "状态"])
        self.account_table.horizontalHeader().setStretchLastSection(True)
        list_layout.addWidget(self.account_table)
        
        refresh_button = QPushButton("刷新列表")
        refresh_button.clicked.connect(self.refresh_accounts)
        list_layout.addWidget(refresh_button)
        
        list_group.setLayout(list_layout)
        layout.addWidget(list_group)
        
        self.refresh_accounts()
        return widget

    def create_client_tab(self):
        """创建客户端管理标签页"""
        widget = QWidget()
        layout = QVBoxLayout()
        widget.setLayout(layout)
        
        # 客户端列表
        list_group = QGroupBox("客户端列表")
        list_layout = QVBoxLayout()
        
        self.client_table = QTableWidget()
        self.client_table.setColumnCount(6)
        self.client_table.setHorizontalHeaderLabels([
            "客户端ID", "用户名", "IP地址", "状态", "白名单", "黑名单"
        ])
        self.client_table.horizontalHeader().setStretchLastSection(True)
        list_layout.addWidget(self.client_table)
        
        # 操作按钮
        button_layout = QHBoxLayout()
        
        refresh_button = QPushButton("刷新列表")
        refresh_button.clicked.connect(self.refresh_clients)
        button_layout.addWidget(refresh_button)
        
        button_layout.addStretch()
        
        self.set_whitelist_button = QPushButton("设置白名单")
        self.set_whitelist_button.clicked.connect(self.set_whitelist)
        button_layout.addWidget(self.set_whitelist_button)
        
        self.set_blacklist_button = QPushButton("设置黑名单")
        self.set_blacklist_button.clicked.connect(self.set_blacklist)
        button_layout.addWidget(self.set_blacklist_button)
        
        self.kick_client_button = QPushButton("踢下线")
        self.kick_client_button.clicked.connect(self.kick_client)
        button_layout.addWidget(self.kick_client_button)
        
        list_layout.addLayout(button_layout)
        
        list_group.setLayout(list_layout)
        layout.addWidget(list_group)
        
        self.refresh_clients()
        return widget

    def toggle_server(self):
        """切换服务器状态"""
        if self.server_thread and self.server_thread.is_alive():
            # 停止服务器
            self.socket_server.stop()
            self.server_status_label.setText("服务器状态: 已停止")
            self.server_status_label.setStyleSheet("color: red; font-weight: bold;")
            self.start_server_button.setText("启动服务器")
        else:
            # 启动服务器
            self.server_thread = threading.Thread(target=self.socket_server.start)
            self.server_thread.daemon = True
            self.server_thread.start()
            self.server_status_label.setText("服务器状态: 运行中")
            self.server_status_label.setStyleSheet("color: green; font-weight: bold;")
            self.start_server_button.setText("停止服务器")
            QMessageBox.information(self, "提示", "服务器已启动")

    def add_account(self):
        """添加账号"""
        username = self.new_username_input.text().strip()
        password = self.new_password_input.text().strip()
        
        if not username or not password:
            QMessageBox.warning(self, "警告", "请输入用户名和密码")
            return
        
        success, message = self.account_manager.create_account(username, password)
        if success:
            QMessageBox.information(self, "成功", message)
            self.new_username_input.clear()
            self.new_password_input.clear()
            self.refresh_accounts()
        else:
            QMessageBox.warning(self, "失败", message)

    def refresh_accounts(self):
        """刷新账号列表"""
        accounts = self.account_manager.list_accounts()
        self.account_table.setRowCount(len(accounts))
        
        for i, account in enumerate(accounts):
            self.account_table.setItem(i, 0, QTableWidgetItem(account.get('username', '')))
            self.account_table.setItem(i, 1, QTableWidgetItem(account.get('status', 'unknown')))

    def refresh_clients(self):
        """刷新客户端列表"""
        clients = self.client_manager.list_clients()
        self.client_table.setRowCount(len(clients))
        
        for i, client in enumerate(clients):
            self.client_table.setItem(i, 0, QTableWidgetItem(client.get('client_id', '')))
            self.client_table.setItem(i, 1, QTableWidgetItem(client.get('username', '')))
            self.client_table.setItem(i, 2, QTableWidgetItem(client.get('ip_address', '')))
            self.client_table.setItem(i, 3, QTableWidgetItem(client.get('status', 'unknown')))
            self.client_table.setItem(i, 4, QTableWidgetItem("是" if client.get('whitelist') else "否"))
            self.client_table.setItem(i, 5, QTableWidgetItem("是" if client.get('blacklist') else "否"))

    def set_whitelist(self):
        """设置白名单"""
        current_row = self.client_table.currentRow()
        if current_row < 0:
            QMessageBox.warning(self, "警告", "请选择要操作的客户端")
            return
        
        client_id = self.client_table.item(current_row, 0).text()
        current_status = self.client_table.item(current_row, 4).text()
        new_status = current_status != "是"
        
        self.client_manager.set_whitelist(client_id, new_status)
        QMessageBox.information(self, "成功", f"已{'添加' if new_status else '移除'}白名单")
        self.refresh_clients()

    def set_blacklist(self):
        """设置黑名单"""
        current_row = self.client_table.currentRow()
        if current_row < 0:
            QMessageBox.warning(self, "警告", "请选择要操作的客户端")
            return
        
        client_id = self.client_table.item(current_row, 0).text()
        current_status = self.client_table.item(current_row, 5).text()
        new_status = current_status != "是"
        
        self.client_manager.set_blacklist(client_id, new_status)
        QMessageBox.information(self, "成功", f"已{'添加' if new_status else '移除'}黑名单")
        self.refresh_clients()

    def kick_client(self):
        """踢客户端下线"""
        current_row = self.client_table.currentRow()
        if current_row < 0:
            QMessageBox.warning(self, "警告", "请选择要操作的客户端")
            return
        
        client_id = self.client_table.item(current_row, 0).text()
        
        # 发送断开消息
        if self.socket_server.send_to_client(client_id, {'action': 'disconnect'}):
            self.client_manager.update_client_status(client_id, 'offline')
            QMessageBox.information(self, "成功", "客户端已下线")
            self.refresh_clients()
        else:
            QMessageBox.warning(self, "失败", "无法断开客户端连接")

    def start_refresh_timer(self):
        """启动自动刷新定时器"""
        self.refresh_timer = QTimer()
        self.refresh_timer.timeout.connect(self.refresh_clients)
        self.refresh_timer.start(5000)  # 每5秒刷新一次

    def closeEvent(self, event):
        """关闭事件"""
        if self.server_thread and self.server_thread.is_alive():
            self.socket_server.stop()
        self.db.close()
        event.accept()


def main():
    app = QApplication(sys.argv)
    
    window = AdminServerWindow()
    window.show()
    
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

